package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter
public class EmployeeFilter implements Filter {
    //设置支持通配符
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request =(HttpServletRequest)servletRequest;
        HttpServletResponse response =(HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        String[] str =new String[]{
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout"
        };
        boolean check = check(str, requestURI);
        //查看是否有跟白名单相同的
        if (check){
            //相同 放行
            filterChain.doFilter(request,response);
            return;
        }

        //在登录状态中
        if (request.getSession().getAttribute("employee")!=null){
            filterChain.doFilter(request,response);
            return;
        }
        response.getWriter().write(JSON.toJSONString("NOTLOGIN"));
    }

    public boolean check(String[] str, String requestURI){
        for (String s : str) {
            boolean match = PATH_MATCHER.match(s, requestURI);
             if (match){
                 return true;
             }
        }
        return false;
    }
}
